package cn.talk.socket.service;

import org.apache.commons.lang.RandomStringUtils;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class Service {

    Map<String, Socket> socketMap = new HashMap<>();
    ServerSocket serverSocket = null;

    public Service(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }

    public void crate() throws IOException {
        Socket socket = serverSocket.accept();
        String id = RandomStringUtils.randomAlphanumeric(5);
        socketMap.put(id, socket);
        System.out.println("进入一个用户,id=" + id + "，当前用户数量：" + socketMap.size());
        new Thread(new Service_Listen(socket, id, this), id).start();
    }

    public void send(String sourceId, String message, String sendId) throws IOException {
        Socket socket = socketMap.get(sendId);
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(message + "-" + sourceId);
        oos.flush();
    }

    public void out(String sourceId) {
        Thread[] ts = new Thread[Thread.activeCount()];
        Thread.enumerate(ts);
        for (Thread t : ts) {
            if (t.getName().equals(sourceId)) {
                System.out.println("从主线程中找到名为" + sourceId + "的线程 状态为: " + t.getState()+"，尝试执行死刑");
                t.interrupt();
                System.out.println("已经行刑");
                this.socketMap.remove(sourceId);
                System.out.println("已经遗弃socket");
            }
        }
    }
}

